import {Button, Card, Col, List, Drawer, notification, Row, Tabs, message, TabsProps} from 'antd';
import React, {useEffect, useState} from 'react';
import {  history } from '@umijs/max';
import {
    billRecordUsingGet,
    getCountStatisticsUsingGet,
    invokerecordTotalUsingGet
} from "@/services/openAPI-backend/dateStatisticsController";
import {getLoginUserUsingGet, getPaySumUsingGet} from "@/services/openAPI-backend/userController";
import ReactECharts from "echarts-for-react";
import {keyframes} from "antd-style";


const onChange = (key: string) => {};

const userBill: React.FC = () => {
    const [imageUrl, setImageUrl] = useState<string>();

    let imminentUser = JSON.parse(sessionStorage.getItem('loginUser'));
    const [currentUser, setCurrentUser] = useState<API.User>({ imminentUser });
    const [ListDrawOpen, setListDrawOpen] = useState<boolean>(false)
    const [totalCost, setTotalCost] = useState<number>();
    const [invokeInterface, setInvokeInterface] = useState<API.BillRecordVO[]>();
    const [invokeInterfaceList, setInvokeInterfaceList] = useState<API.UserInvokeCount[]>();
    const [loading, setLoading] = useState(true);
    const [Data, setData] = useState<{ value: number; name: string}[]>();
    const [paySum,setPaySum] = useState<number>();
    const getPaySum = async ()=>{
        try{
            const res = await getPaySumUsingGet();
            if(res.data)
                setPaySum(res.data);
        }catch (e) {
            console.log(e);
        }
    }
    const getLoginUser = async () => {
        try {
            const res = await getLoginUserUsingGet();
            sessionStorage.setItem('loginUser', JSON.stringify(res.data));
            imminentUser = JSON.parse(sessionStorage.getItem('loginUser'));
            if (imminentUser.gender === 0) imminentUser.gender = '男';
            else imminentUser.gender = '女';
            setCurrentUser(imminentUser);
        }catch (e) {
            history.push('/user/login')
        }
    };
    const getInvokeInterfaceList = async () => {
        try{
            const res = await getCountStatisticsUsingGet();
            if(res.data) {
                setInvokeInterfaceList(res?.data);
                const chartData = Array.from(res.data).map((item) => {

                    return {
                        value: item.totalCost,
                        name: item.interfaceInfoName,
                    };
                });
                setData(chartData);
            }
            else
                setInvokeInterfaceList(null)
        }catch (e) {

        }
    };
    const getInvokeInterface = async () => {
        try{
            const res = await billRecordUsingGet();
            if(res.data)
                setInvokeInterface(res.data);
            else
                notification.error({
                    message: '获取总调用次数失败',
                    description: '请检查网络连接',
                });
        }catch (e) {

        }
    };
    const ListDrawer = () => {
        setListDrawOpen(true);
    };
    const getToalCost = async () => {
        try{
            const res = await invokerecordTotalUsingGet();
            if(res.data)
                setTotalCost(res.data);
            else
                setTotalCost(0)
        }catch (e) {

        }
    };
    function tryLegacyCopy(url) {
        // 创建一个隐藏的textarea元素
        const textarea = document.createElement('textarea');
        textarea.value = url;
        textarea.style.position = 'fixed'; // 防止影响页面布局
        textarea.style.top = 0;
        textarea.style.left = 0;
        textarea.style.width = '1px';
        textarea.style.height = '1px';
        textarea.style.padding = 0;
        textarea.style.border = 'none';
        textarea.style.outline = 'none';
        textarea.style.boxShadow = 'none';
        textarea.style.background = 'transparent';

        document.body.appendChild(textarea);
        textarea.select();

        // 尝试复制
        const copied = document.execCommand('copy');

        // 清理
        document.body.removeChild(textarea);

        if (copied) {
            message.success('管理员邮箱已复制到剪切板');
        } else {
            console.error('Failed to copy URL to clipboard with the legacy method');
            // 可以进一步处理错误情况
        }
    }
    const copyUrl = (url: string) => {
        if (navigator.clipboard && window.isSecureContext) {
            navigator.clipboard
                .writeText(url)
                .then(() => {
                    message.success('管理员邮箱已复制到剪切板');
                })
                .catch((error) => {
                    console.error('Error copying URL to clipboard:', error);
                    // 处理错误，例如显示警告信息
                });
        }else{
            tryLegacyCopy(url);
        }
    };
    useEffect(() => {
        getToalCost();
        getInvokeInterface();
        getInvokeInterfaceList();
        getPaySum();
        getLoginUser();
    }, []);
    const option = {
        tooltip: {
            trigger: 'item'
        },
        legend: {
            top: '5%',
            left: 'center',
            left: '85%'
        },
        series: [
            {
                name: 'Access From',
                type: 'pie',
                radius: ['40%', '70%'],
                avoidLabelOverlap: false,
                itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2,
                    fontSize: 20
                },
                label: {
                    show: false,
                    position: 'center'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: 40,
                        fontWeight: 'bold'
                    }
                },
                labelLine: {
                    show: false
                },
                data: Data ? Data.sort(function (a, b) {
                    return a.value - b.value;
                }) : [],
            },
        ]};
    const fadeIn = keyframes`
        0% {
            clip-path: inset(0 0 100% 0); /* 初始时，元素被裁剪仅显示左侧边缘 */
        }
        100% {
            clip-path: inset(0 0 0 0); /* 完全展开，无裁剪 */
        }
    `;
    /**
     * 每个单独的卡片，为了复用样式抽成了组件
     * @param param0
     * @returns
     */
    const items: TabsProps['items'] = [
        {
            key: '1',
            label: (
                <span className="tab-label1" style={{ fontSize: 20, margin: 30, marginLeft: 30 }}>
          列表记录
        </span>
            ),
            children: (
                <Card style={{
                    width: '100%',
                    marginBottom: 10
                }}>
                    <p style={{fontSize: 20, marginBottom: 15, fontWeight: 'bold',width: '100%',maxHeight: 800, overflowY: 'auto'}}>
                        您调用过的接口为:
                        <List
                            dataSource={invokeInterfaceList}
                            renderItem={(item,index) => (
                                <List.Item key={index} style={{ animation: `${fadeIn} 0.5s cubic-bezier(0.4, 0, 0.2, 1) both`,
                                    animationDelay: `${index * 0.1}s`,}}>
                                    <List.Item.Meta
                                        title={<a href={`/interface_info/${item.interfaceInfoId}`}>{item.interfaceInfoName}</a>}
                                        description={<a
                                            style={{color: 'gray'}}>总调用次数:{item.invokeNum}</a>
                                        }
                                    />
                                    <a style={{color: 'gray',marginRight: 10}}>$ {item?.totalCost}</a>
                                </List.Item>
                            )}
                        />
                    </p>
                </Card>
            ),
        },
        {
            key: '2',
            label: (
                <span className="tab-label2" style={{ fontSize: 20, margin: 30 }}>
          图表记录
        </span>
            ),
            children: (
                <Card style={{
                    width: '100%',
                    marginBottom: 10
                }}>
                    <p style={{ fontSize: '24px',fontWeight:'bold',textAlign:'center',marginRight:'4%'}}>接口消费总记录</p>
                    <ReactECharts loadingOption={{ showLoading: loading }} option={option} />
                </Card>
            ),
        },
    ];
    const fade = keyframes`
        0% {
            opacity: 0;
        }
        100% {
            opacity: 1;
        }
    `;
    return (
        <Card style={{animation: `${fade} 0.5s ease-in-out`}}>
            <p style={{fontSize: 22, fontWeight: 'bold', marginBottom: 15}}>总览</p>
            <Row gutter={24}>

                <Col span={8}><Card style={{width: '100%', height: '100%'}}>
                    <p style={{fontSize: 15, marginLeft: 5, marginBottom: 6}}>
                        账户可用额度：
                    </p>
                    <p style={{fontSize: 27, marginTop: 8, marginLeft: 5, marginBottom: 5}}><a style={{
                        color: 'black',
                        fontWeight: 'bold', marginRight: '5%'
                    }}>$ {currentUser.remainingPoints}</a></p>
                    <p style={{fontSize: 15, marginLeft: 5, marginBottom: 5}}>
                        总消费：
                    </p>
                    <p style={{fontSize: 27, marginTop: 8, marginLeft: 5, marginBottom: 15}}><a style={{
                        color: 'black',
                        fontWeight: 'bold', marginRight: '5%'
                    }}>$ {totalCost}</a></p>
                    <Button style={{marginLeft: 0}} onClick={() => {
                        history.push('/marketConfig/market')
                    }} ghost={'true'} size={'small'} type={'primary'}>去充值</Button>
                    <Button ghost={'true'}
                            style={{marginLeft: 10}}
                            size={'small'}
                            onClick={() => {
                                ListDrawer();
                            }}
                            type={'primary'}>收支详情</Button>
                </Card></Col>
                <Col span={8}><Card style={{width: '100%', height: '100%'}}>
                    <p style={{
                        fontSize: 15, marginLeft: 5, marginBottom: 6
                    }}>总需还款金额：</p>
                    <p style={{fontSize: 27, marginTop: 8, marginLeft: 5, marginBottom: 15}}><a style={{
                        color: 'black',
                        fontWeight: 'bold', marginRight: '5%'
                    }}> $ {currentUser.remainingPoints >= 0 ? '0.00' : 0 - currentUser.remainingPoints}</a></p>
                    <p style={{
                        fontSize: 15, marginLeft: 5, marginBottom: 6
                    }}>您的账本状态：</p>
                    <p style={{fontSize: 27, marginTop: 8, marginLeft: 5, marginBottom: 15}}><a style={{
                        color: 'black',
                        fontWeight: 'bold', marginRight: '5%'
                    }}> {currentUser.remainingPoints <= 0.1 ? "欠费" : "Normal"}</a></p>
                </Card></Col>
                <Col span={8}><Card style={{width: '100%', height: '100%'}}>
                    <p style={{
                        fontSize: 15, marginLeft: 5, marginBottom: 6
                    }}>节省计划已节省：</p>
                    {currentUser.vip===0?(<><p style={{fontSize: 27, marginTop: 8, marginLeft: 5, marginBottom: 15}}><a
                        style={{
                            color: 'black',
                            fontWeight: 'bold', marginRight: '5%'
                        }}> {currentUser.remainingPoints <= 0.1 ? "欠费" : "您尚未开通平台会员"}</a></p>
                        <p style={{
                            fontSize: 15, marginLeft: 5, marginBottom: 6
                        }}>您的总充值：</p>
                        <p style={{fontSize: 27, marginTop: 8, marginLeft: 5, marginBottom: 15}}><a style={{
                            color: 'black',
                            fontWeight: 'bold', marginRight: '5%'
                        }}>$ {paySum}</a></p>
                        <Button style={{marginLeft: 0}} onClick={() => {
                            message.success('管理员邮箱：3157115439@qq.com');
                            copyUrl('3157115439@qq.com')
                        }} ghost={'true'} size={'small'} type={'link'}>有疑问？联系管理员</Button>
                        <Button style={{marginLeft: 0}} onClick={() => {
                            history.push('/marketConfig/vip')
                        }} ghost={'true'} size={'small'} type={'primary'}>加入平台会员</Button></>) : (
                        <><p style={{fontSize: 27, marginTop: 8, marginLeft: 5, marginBottom: 15}}><a style={{
                            color: 'black',
                            fontWeight: 'bold', marginRight: '5%'
                        }}>￥ 20.3 元</a></p>
                            <p style={{
                                fontSize: 15, marginLeft: 5, marginBottom: 6
                            }}>您的总充值：</p>
                            <p style={{fontSize: 27, marginTop: 8, marginLeft: 5, marginBottom: 15}}><a style={{
                                color: 'black',
                                fontWeight: 'bold', marginRight: '5%'
                            }}>$ {paySum}</a></p>
                            <Button style={{marginLeft: 0}} onClick={() => {
                                message.success('管理员邮箱：3157115439@qq.com');
                                copyUrl('3157115439@qq.com')
                            }} ghost={'true'} size={'small'} type={'link'}>有疑问？联系管理员</Button>
                        </>
                    )}
                    <Drawer
                        open={ListDrawOpen}
                        size={'large'}
                        onClose={() => {
                            setListDrawOpen(false);
                        }}
                    >
                        <div
                            id="scrollableDiv"
                            style={{
                                height: '100%',
                                overflow: 'auto',
                                maxHeight: '100%',
                                WebkitOverflowScrolling: 'touch',
                            }}
                        >
                            <List
                                dataSource={invokeInterface}
                                renderItem={(item) => (
                                    <List.Item key={item.createtime}>
                                        <List.Item.Meta
                                            title={<a style={{ fontSize: 15 }}>{item.interfaceInfoName}</a>}
                                            description={new Date(item.createtime).toLocaleString('zh-CN', {
                                                year: 'numeric',
                                                month: '2-digit',
                                                day: '2-digit',
                                                hour: '2-digit',
                                                minute: '2-digit',
                                                hour12: false,
                                            })}
                                        />
                                        <div> </div>
                                        <p style={{ fontWeight: 'bold', color: 'gray' }}>-{item?.invokeCosts}$</p>
                                    </List.Item>
                                )}
                            />
                        </div>
                    </Drawer>
                </Card></Col>

            </Row>
            <Row>

                <Card style={{width: '100%', height: '90%', marginTop: 20}}>
                    <p style={{fontWeight:'bold',fontSize: 20, marginLeft: 5, marginBottom: 6,textAlign: 'center'}}>费用总览</p>
                    <Tabs
                        defaultActiveKey="1"
                        items={items}
                        onChange={onChange}
                        style={{width: '100%', fontSize: 16, marginleft: 30}}
                    ></Tabs>
                </Card>
            </Row>
        </Card>

    );
};

export default userBill;
